<!DOCTYPE html>
<html>

<head>
	<meta http-equiv="X-UA-Compatible" content="IE=8" />
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="author" content="TengQiu Li" />
	<title>Upload Image</title>
	<style type="text/css">
		html,
		body {
			padding-top: 0;
			padding-bottom: 0;
			margin-bottom: 0;
			margin-top: 0;
			overflow: auto;
		}

		progress {
			height: 1px;
			width: 100%;
			vertical-align: middle;
			border: 0px solid transparent;
			background: #bedffd;
			color: #00771a;
			border-radius: 2px;
			overflow: hidden;

		}

		progress::-webkit-progress-bar {
			background: #bedffd;
		}

		progress::-webkit-progress-value,
		progress::-moz-progress-bar {
			background: #00771a;
		}

		progress {
			display: block;
			margin: 2px 0;
		}

		.list-group {
			display: block;
			margin: 5px 0;
		}

		.list-group>div {
			margin: 3px;
			padding: 5px;
		}

		.list-group>div {
			border-bottom: 1px solid #ddd;
		}

		.uploading-item {
			background: #f3f3f3;
			box-shadow: 0 0 2px #cecece;
		}

		.error-item {
			background: #ffe1e1;
		}

		span[name='MESSAGE'] {
			margin: 0 2ex;
		}

		.error-item span[name='MESSAGE'] {
			color: red;
			font-weight: bold
		}

		a {
			text-decoration: none;
		}

		span[name="UPLOADED"]:not(:empty)::after {
			content: ' / ';
		}

		span[name="UPLOADED_PERCENT"]:not(:empty)::after {
			content: '%';
		}

		.delete {
			font-size: large;
			margin-right: 5px;
			cursor: pointer;
		}
	</style>
	<script src="uploadApi.js" type="text/javascript"></script>
	<script type="text/javascript">
		var a = location.search.substring(1).split('&'),
			urlPath = location.pathname,
			//参数,会同时作为POST变量提交至接收页
			GET = {
				'url': '',
				'max_size': '2 MB', //单文件最大尺寸
				'exts': '*.*', // *.jpg;*.gif;*.png;*.jpeg
				'description': '文件',
				'field_name': 'file',
				'file_max_count': 0, //允许上传文件个数, 0表示可以任意
				'upload_type': '',//上传的调用类型 // link|image|flash|video|music
			};
		//----------------
		urlPath = urlPath.substr(0, urlPath.lastIndexOf('/') + 1);
		for (var i = a.length - 1; i >= 0; i--) {
			var p = a[i].indexOf('=');
			if (p > 0) {
				GET[a[i].substr(0, p)] = decodeURIComponent(a[i].substring(p + 1));
			}
		}


		function fixHeight() {
			if (window.top == window) return;
			var h = 18 + document.body.offsetHeight;
			if (h > 800) h = 800;
			window.frameElement.style.minHeight = h + 'px';
		}
		//-----------------------------
		//file={post:{},id:'唯一ID',creationdate:'文件创建时间戳',name:'文件名',index:'在队列中的位置索引', type:'.文件后缀', filestatus:-1,modificationdate:'文件修改时间戳',size:'文件大小'}
		function asFilesUploader(obj) {
			var uiElement = document.createElement('div'), htm;
			// htm = '<ul name="FILES_LIST"  class="list-group">' +
			// 	'<li name="WAITING" class="list-item"><a href="javascript:void(0)" NAME="REMOVE" class="button delete" title="取消">取消</a> <strong>{TITLE}</strong> <i>{FILE_SIZE}</i> <span name="MESSAGE">等待...</span></li>' +
			// 	'<li name="UPLOADING" class="list-item"><a href="javascript:void(0)" NAME="REMOVE" class="button delete" title="取消">取消</a> <strong>{TITLE}</strong> <i>{FILE_SIZE}</i> <span name="MESSAGE">等待...</span></li>' +
			// 	'<li name="RESULT"  class="list-item" data-value="{URL}" title="{TITLE}"><b title="删除" NAME="REMOVE" ></b> <a href="{URL}" target="_blank">{TITLE}</a></li>' +
			// 	'</ul>' +
			// 	'<button name="UPLOAD_BTN" > + 上传 </button>' +
			// 	'<button name="CANCEL_ALL_BTN" style="display:none"> 取消所有 </button>';
			//if(obj.getAttribute('data-ui')){
			htm = document.querySelector(obj.getAttribute('data-ui')).innerHTML;
			//} 

			uiElement.innerHTML = htm;
			uiElement.className = '-uploads-files ' + obj.className;
			var filesList = uiElement.querySelector('[name="FILES_LIST"]'),
				uploadButton = uiElement.querySelector('[name="UPLOAD_BTN"]'),
				cancelAllButton = uiElement.querySelector('[name="CANCEL_ALL_BTN"]'),
				uploadInput = document.createElement('input');
			//--
			filesList._tplResult = filesList.firstElementChild.outerHTML;
			filesList._tplWaiting = filesList.lastElementChild.outerHTML;
			//filesList._tplUploading = filesList.firstChild.nextSibling.outerHTML;



			htm = '';
			var a = obj.value.trim().split("\n"), aa;
			for (var i = 0; i < a.length; i++) {
				a[i] = a[i].trim();
				if ('' == a[i]) continue;
				aa = a[i].split("#", 2);
				if (aa.length < 2) aa[1] = a[i].split('/').pop();
				htm += filesList._tplResult.replace(/\{URL\}/g, aa[0]).replace(/\{TITLE\}/g, aa[1]);
			}
			filesList.innerHTML = htm;
			filesList.updateValue = function () {
				var values = [], v;
				this.childNodes.forEach(function (e) {
					if (e.getAttribute('data-value')) values.push(e.getAttribute('data-value') + '#' + e.getAttribute('title'));
				});
				v = values.join("\n")
				if (v != obj.value) {
					obj.value = v;
					//QUI.dispatchEvent(obj, 'change');
				}
			}
			filesList.childNodes.forEach(function (e) {
				var a = e.querySelector('[name="REMOVE"]');
				if (a) a.onclick = function () {
					//QUI.closePanel(e, function(){filesList.updateValue()});
					//e.close();
					filesList.removeChild(e);
					filesList.updateValue();
				};
			});


			obj.parentNode.insertBefore(uiElement, obj);
			obj.addEventListener('change', function (e) {

			});

			uploadButton.onclick = function (event) {
				this.parentNode._uploadInput.click();
			}

			uploadInput.type = "file";
			uploadInput.style.display = "none";
			uploadInput.accept = obj.getAttribute("accept");
			uploadInput.multiple = true;
			uploadInput.name = "file";

			if (obj.getAttribute('data-fieldName')) uploadInput.name = obj.getAttribute('data-fieldName');

			document.body.appendChild(uploadInput);
			var maxsize = obj.getAttribute('data-maxfilesize'), r = /[gmk]/i;
			var t = r.exec(maxsize);
			maxsize = parseInt(maxsize);
			if (t) {
				switch (t[0].toLowerCase()) {
					case 'k': maxsize *= 1024; break;
					case 'm': maxsize *= 1024 * 1024; break;
					case 'g': maxsize *= 1024 * 1024 * 1024; break;
				}
			}



			uploadInput.onchange = function () {
				if (this.files.length < 1) return;
				var div = document.createElement('DIV'), waitingElementUI, index, item;
				for (index = 0; index < this.files.length; index++) {
					item = this.files[index];
					div.innerHTML = filesList._tplWaiting.replace(/\{TITLE\}/g, item.name).replace(/\{FILE_SIZE\}/g, item.size);
					waitingElementUI = div.firstChild;
					filesList.appendChild(waitingElementUI);
					waitingElementUI.setAttribute('data-waiting-index', index);
					waitingElementUI._formData = new FormData();
					waitingElementUI._formData.append(this.name, item);
					var a = waitingElementUI.querySelector('[name="REMOVE"]');
					if (a) {
						a.p = waitingElementUI;
						a.onclick = function () { filesList.removeChild(this.p); };
					}
					if (item.size > maxsize) {
						waitingElementUI.removeAttribute('data-waiting-index');
						waitingElementUI.classList.add('error-item');
						var e = waitingElementUI.querySelector("[name='MESSAGE']");
						if (e) e.innerHTML = '文件大小超限';
					}
				}
				cancelAllButton.style.display = '';
				uploadButton.style.display = 'none';
				cancelAllButton.onclick = function () {
					if (!confirm('真的要取消吗?')) return;
					var a = filesList.querySelectorAll('[data-waiting-index]');
					a.forEach(function (item) { filesList.removeChild(item) });
					a = filesList.querySelector('[data-uploading]');
					if (a) a._XMLHttpRequest.abort();
				}
				var uploadNext = function () {
					var uploadingElementUI = filesList.querySelector('[data-waiting-index]');
					if (!uploadingElementUI) {//没上传队列了
						cancelAllButton.style.display = 'none';
						uploadButton.style.display = '';
						return;
					}
					uploadingElementUI.removeAttribute('data-waiting-index');
					uploadingElementUI.setAttribute('data-uploading', '1');
					uploadingElementUI.classList.add('uploading-item');

					var progress = uploadingElementUI.querySelector('progress'),
						eMessage = uploadingElementUI.querySelector('[name="MESSAGE"]'),
						eUpload = uploadingElementUI.querySelector('[name="UPLOADED"]'),
						eUploadPercent = uploadingElementUI.querySelector('[name="UPLOADED_PERCENT"]'),
						eCancelBtn = uploadingElementUI.querySelector('[name="REMOVE"]')
					xr = new XMLHttpRequest(),
						notify = function (msg, type) {
							console.log(msg);
						},
						uploadProgress = function (e) {
							if (progress) progress.value = e.loaded / e.total;

							if (eUpload) eUpload.innerHTML = e.loaded;
							if (eUploadPercent) eUploadPercent.innerHTML = Math.floor(100 * progress.value);
						},
						uploadComplete = function (e) {
							progress.value = 1;

							if (this.status == 404) {
								notify("上传失败, 目标网址不存在", "failt");
								uploadNext();
								return;
							}

							var result, retStr = e.target.responseText;
							try {
								// {url:"", name:"", file:"", message:"succ", error:"0" }
								result = eval('[' + retStr + ']')[0];
								if (result.error == 0) {
									var d = document.createElement('DIV'), e;
									d.innerHTML = filesList._tplResult.replace(/\{URL\}/g, result.url).replace(/\{TITLE\}/g, result.name);
									e = d.firstChild;
									e.setAttribute('data-value', result.url);
									e.title = result.name;
									var a = e.querySelector('[name="REMOVE"]');
									if (a) a.onclick = function () {
										filesList.removeChild(e);
										filesList.updateValue();
									};
									filesList.replaceChild(e, uploadingElementUI);
									filesList.updateValue();
									if(GET.upload_type=='image') insertResult(result.url);
								} else {
									notify("上传 " + result.name + "失败<br>" + result.message, "error");
									filesList.removeChild(uploadingElementUI);
								}
							}
							catch (e) {

								notify('出错, 服务器返值:\n' + retStr, 'failt');
								filesList.removeChild(uploadingElementUI);
							}
							//uploadingElementUI.innerHTML='';
							//uploadingElementUI=null;
							uploadNext();

						},
						uploadFailed = function (e) {
							console.log('上传失败');
							//notify("上传失败", "failt");
							uploadingElementUI.parentNode.removeChild(uploadingElementUI);
							uploadNext();

						},
						uploadAbort = function (e) {
							notify("已取消", "info");
							//QUI.closePanel(uploadingElementUI);
							uploadingElementUI.parentNode.removeChild(uploadingElementUI);
							uploadNext();
							//window.setTimeout(_uploadNext, 50);
						};

					uploadingElementUI._XMLHttpRequest = xr;
					if (progress) progress.value = 0;
					if (eMessage) eMessage.innerHTML = '上传中';
					if (eCancelBtn) eCancelBtn.onclick = function () { if (confirm("真的要取消上传吗?")) xr.abort(); }

					xr.upload.addEventListener("progress", uploadProgress, false);
					xr.addEventListener("load", uploadComplete, false);
					xr.addEventListener("error", uploadFailed, false);
					xr.addEventListener("abort", uploadAbort, false);
					//r.open("POST", CFG.upload_url);
					var upload_url = "/upload.php";
					if (obj.getAttribute('data-uploadurl')) upload_url = obj.getAttribute('data-uploadurl');
					xr.open("POST", upload_url);

					xr.send(uploadingElementUI._formData);
				}
				uploadNext();
			}
			uiElement._uploadInput = uploadInput;
			uiElement._target = obj;
			obj.style.display = "none";
		}
	</script>

</head>

<body>
	<div id="upload-ui" style="display:none">
		<DIV name="FILES_LIST" class="list-group">
			<DIV name="RESULT" class="list-item" data-value="{URL}" title="{TITLE}"><b title="删除" class="delete" NAME="REMOVE"></b> <a
					href="{URL}" onclick="selectResult(this.href);return false;">{TITLE}</a> <a href="{URL}"
					target="_blank" onclick="selectResult(this.href);" style="color:#333">查看</a> </DIV>
			<DIV name="RESULT" class="list-item" data-value="{URL}" title="{TITLE}"><b title="删除" NAME="REMOVE"></b> <a
					href="{URL}" target="_blank">{TITLE}</a></DIV>
			<DIV name="RESULT" class="list-item" data-value="{URL}" title="{TITLE}"><b title="删除" NAME="REMOVE"></b> <a
					href="{URL}" target="_blank">{TITLE}</a></DIV>
			<DIV name="WAITING" class="error-item"><b NAME="REMOVE" class="button delete" title="取消">&times;</b>
				<strong>{TITLE}</strong> <i>{FILE_SIZE}</i> <span name="MESSAGE">文件太大了</span>
				<progress value="0"></progress></DIV>
			<DIV name="WAITING" class="uploading-item"><b NAME="REMOVE" class="button delete" title="取消">&times;</b>
				<strong>{TITLE}</strong> <i>{FILE_SIZE}</i> <span name="MESSAGE">正在上传 23%</span>
				<div style="line-height:3px;"><progress value="0.23"></progress></div>
			</DIV>
			<DIV name="WAITING" class="list-item"><b NAME="REMOVE" class="delete" title="取消">&times;</b>
				<strong>{TITLE}</strong> <i style="float:right"><span name="UPLOADED"></span>{FILE_SIZE}</i> <span
					name="MESSAGE">排队中</span><span name="UPLOADED_PERCENT"></span>
				<progress value="0"></progress></DIV>
		</DIV>
		<button name="UPLOAD_BTN"> + 上传 </button>
		<button name="CANCEL_ALL_BTN" style="display:none"> 取消所有 </button>
	</div>

	<textarea style="display:none" id="fileslist" data-uploadurl="../upload.php" data-fieldName="file"
		data-ui="#upload-ui" accept="*" data-maxFilesize="10m"></textarea>
	<script type="text/javascript">
		//new SWFUpload(setting);
		fixHeight();
		var obj = document.getElementById('fileslist');
		switch (GET.upload_type) {
			case 'image': obj.setAttribute('accept', 'image/*'); break;
			case 'video': obj.setAttribute('accept', 'video/*'); break;
			case 'music': obj.setAttribute('accept', 'audio/*'); break;
			case 'flash': obj.setAttribute('accept', 'flash/*'); break;
			case 'link': obj.setAttribute('accept', '*'); break;
			default: obj.setAttribute('accept', '*');
		}
		if (GET.url) obj.setAttribute('data-uploadurl', GET.url);
		if (GET.field_name) obj.setAttribute('data-fieldname', GET.field_name);
		if (GET.max_size) obj.setAttribute('data-maxfilesize', GET.max_size);

		asFilesUploader(obj);
		//document.getElementById('exts_text').innerHTML = GET.exts;
	</script>
</body>

</html>